聚合函數就是將資料分組後, 進行運算得出統計結果, 用於取大值、取小值、取平均值、取資料筆數、總數、變異數、50百分位數等等。【注意】使用聚合函數計算統計結果前, 要確認資料型別是數字, 若為字串可能誤判(9>12, MAX=9)
| 保留字 | Function | 
|---|---|
| MAX | 取分組資料中 最大值 | 
| MIN | 取分組資料中 最小值 | 
| SUM | 取分組資料中 加總結果 | 
| AVG | 取分組資料中 平均值 | 
| count | 取 資料總比數 | 
-- 1. 根據數學成績檔案, 取得所有學生的:數學平均、最大、最小、全班總分、學生數
with Math_Score as (
    select 'Amy' name, 67 score
    union all
    select 'Oleve' name, 77 score
    union all
    select 'Jake' name, 78 score
    union all
    select 'James' name, 87 score
    union all
    select 'Black' name, 59 score
)
select AVG(score), MAX(score),MIN(score), SUM(score), count(1) 
from Math_Score
;
-- output
AVG(SCORE) MAX(SCORE) MIN(SCORE) SUM(SCORE)   COUNT(1)
73.6	   87	      59	      368	     5
-- 2. 根據年紀, 取得`同齡`學生的:數學平均、最大、最小、全班總分、學生數
with Math_Score as (
    select 'Amy' name, 15 year, 67 score
    union all
    select 'Oleve' name, 15 year , 77 score
    union all
    select 'Jake' name, 15 year, 78 score
    union all
    select 'James' name, 16 year, 87 score
    union all
    select 'Black' name, 16 year, 59 score
)
select year, AVG(score), MAX(score),MIN(score), SUM(score), count(1) 
from Math_Score
where 1=1
group by year
;
-- output
YEAR   AVG(SCORE)   MAX(SCORE)   MIN(SCORE)   SUM(SCORE)   COUNT(1)
   15	   74	       78	      67	         222   		3
   16	   73	       87    	  59	         146	    2
類似一般查詢的 where 條件語法, 對於分組後的結果想要再進行資料過濾, 可以使用 having 函數來完成。
-- 3. 根據年紀, 取得該年紀有人數學成績大於80分的年齡層數學平均、最大、最小、全班總分、學生數
with Math_Score as (
    select 'Amy' name, 15 year, 67 score
    union all
    select 'Oleve' name, 15 year , 77 score
    union all
    select 'Jake' name, 15 year, 78 score
    union all
    select 'James' name, 16 year, 87 score
    union all
    select 'Black' name, 16 year, 59 score
)
select year, AVG(score), MAX(score),MIN(score), SUM(score), count(1) 
from Math_Score
where 1=1
group by year
having MAX(score) >= 80
;
-- output
YEAR   AVG(SCORE)   MAX(SCORE)   MIN(SCORE)     SUM(SCORE)  	 COUNT(1)
16	   73	        87	          59	        146		          2